package io.renren.util;

import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.squareup.okhttp.*;
import io.renren.vo.RespModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HystrixPostUtil extends HystrixCommand<String> {


	public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json");
	private Map<String, Object> param;
	private String url;
	private final OkHttpClient client = new OkHttpClient();
	
	public HystrixPostUtil(String url, Map<String, Object> param) {
		super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("UtilService")).andCommandPropertiesDefaults(
				HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(30 * 1000)));
		this.param = param;
		this.url = url;
	}

	@Override
	protected String run() throws Exception {
		Request request = null;

		request = new Request.Builder().url(url).post(RequestBody.create(MEDIA_TYPE_JSON, JSON.toJSONString(param)))
				.build();

		Response response = client.newCall(request).execute();
		if (response.isSuccessful()) {
			String resp = response.body().string();
			return resp;
		} else {
			throw new RuntimeException("http error" + response.code());
		}
	}
	
	protected String getFallback() {
		System.out.println("url:" + url);
		System.out.println("payload:" + JSON.toJSONString(param));
		RespModel respModel = new RespModel("failed", "500", "INTERNAL SERVER ERROR", null);
		return JSON.toJSONString(respModel).toString();
	}

	public static void main(String[] args) {
		List<Long> list = new ArrayList<Long>();
		list.add(0l);
		list.add(1l);
		list.add(2l);
		
		Map<String, Object> comm = new HashMap<String, Object>();
		comm.put("roleIds", list);
		
		String loginResult = new HystrixPostUtil("/menu/queryMenuList", comm).execute();//TODO 地址需要修改
		System.out.println(loginResult);
	}

}
